<template>
  <a-layout class="layout-container">
    <a-layout-sider
      v-model:collapsed="appStore.collapsed"
      :trigger="null"
      collapsible
      class="layout-sider"
    >
      <div class="logo">
        <Logo :is-collapsed="appStore.collapsed" />
      </div>
      <a-menu
        v-model:selectedKeys="selectedKeys"
        theme="dark"
        mode="inline"
        @click="handleMenuClick"
      >
        <a-menu-item key="/dashboard">
          <template #icon>
            <DashboardOutlined />
          </template>
          <span>看板</span>
        </a-menu-item>
        <a-menu-item key="/user">
          <template #icon>
            <UserOutlined />
          </template>
          <span>用户管理</span>
        </a-menu-item>
        <a-menu-item key="/settings">
          <template #icon>
            <SettingOutlined />
          </template>
          <span>系统设置</span>
        </a-menu-item>
        <a-menu-item key="/article">
          <template #icon>
            <FileTextOutlined />
          </template>
          <span>文章管理</span>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-header class="layout-header">
        <div class="header-left">
          <MenuUnfoldOutlined
            v-if="appStore.collapsed"
            class="trigger"
            @click="appStore.toggleCollapsed"
          />
          <MenuFoldOutlined v-else class="trigger" @click="appStore.toggleCollapsed" />
        </div>
        <div class="header-right">
          <a-dropdown>
            <a-avatar-group>
              <a-avatar class="avatar" :size="40">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <div>{{ userStore.userInfo?.username || '用户' }}</div>
            </a-avatar-group>

            <template #overlay>
              <a-menu @click="handleUserMenuClick">
                <a-menu-item key="profile">
                  <UserOutlined />
                  个人中心
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item key="logout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-layout-header>
      <div class="tabs-bar">
        <div class="tabs-container">
          <div
            v-for="tab in tabsStore.tabs"
            :key="tab.path"
            :class="['tab-item', { active: tab.path === tabsStore.activeTab }]"
            @click="handleTabClick(tab.path)"
          >
            <component :is="iconComponents[tab.icon]" v-if="tab.icon" class="tab-icon" />
            <span class="tab-title">{{ tab.title }}</span>
            <CloseOutlined
              v-if="tab.path !== '/dashboard'"
              class="tab-close"
              @click.stop="handleTabClose(tab.path)"
            />
          </div>
        </div>
        <div class="tabs-actions">
          <a-dropdown>
            <DownOutlined class="tabs-action-icon" />
            <template #overlay>
              <a-menu>
                <a-menu-item @click="handleCloseOthers">
                  <CloseCircleOutlined />
                  关闭其他
                </a-menu-item>
                <a-menu-item @click="handleCloseAll">
                  <CloseSquareOutlined />
                  关闭所有
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
      <a-layout-content class="layout-content">
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" v-if="$route.meta.keepAlive" :key="$route.path" />
          </keep-alive>
          <component :is="Component" v-if="!$route.meta.keepAlive" :key="$route.path" />
        </router-view>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Modal, message } from 'ant-design-vue'
import { useAppStore } from '@/stores/app'
import { useTabsStore } from '@/stores/tabs'
import { useUserStore } from '@/stores/user'
import Logo from '@/components/common/Logo.vue'
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  DashboardOutlined,
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  CloseOutlined,
  DownOutlined,
  CloseCircleOutlined,
  CloseSquareOutlined,
  FileTextOutlined,
} from '@ant-design/icons-vue'
import type { MenuInfo } from 'ant-design-vue/es/menu/src/interface'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const tabsStore = useTabsStore()
const userStore = useUserStore()
const selectedKeys = ref<string[]>([route.path])

// Icon 组件映射
const iconComponents: Record<string, any> = {
  DashboardOutlined,
  UserOutlined,
  SettingOutlined,
  FileTextOutlined,
}

// 监听路由变化，添加标签页
watch(
  () => route.path,
  (newPath) => {
    selectedKeys.value = [newPath]
    tabsStore.addTab(route)
  },
  { immediate: true }
)

const handleMenuClick = (info: MenuInfo) => {
  router.push(info.key as string)
}

const handleTabClick = (path: string) => {
  router.push(path)
}

const handleTabClose = (path: string) => {
  const currentIndex = tabsStore.tabs.findIndex((tab) => tab.path === path)
  tabsStore.removeTab(path)

  // 如果关闭的是当前激活的标签页，跳转到前一个或后一个
  if (path === route.path) {
    const tabs = tabsStore.tabs
    if (tabs.length > 0) {
      const targetTab = tabs[Math.max(0, currentIndex - 1)]
      if (targetTab) {
        router.push(targetTab.path)
      }
    }
  }
}
console.log('userStore.userInfo', userStore.userInfo)
const handleCloseOthers = () => {
  tabsStore.closeOtherTabs(route.path)
}

const handleCloseAll = () => {
  tabsStore.closeAllTabs()
  router.push('/dashboard')
}

// 处理用户菜单点击
const handleUserMenuClick = (info: MenuInfo) => {
  if (info.key === 'logout') {
    Modal.confirm({
      title: '确认退出',
      content: '您确定要退出登录吗？',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        await userStore.logout()
        tabsStore.closeAllTabs()
        message.success('已退出登录')
        router.push('/login')
      },
    })
  } else if (info.key === 'profile') {
    message.info('个人中心功能待实现')
  }
}
</script>

<style scoped lang="less">
.layout-container {
  min-height: 100vh;
}

.layout-sider {
  background: #001529;
}

.logo {
  height: 64px;
}

.layout-header {
  background: #fff;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  height: 64px;
}

.header-left {
  display: flex;
  align-items: center;
}

.trigger {
  font-size: 18px;
  cursor: pointer;
  transition: color 0.3s;
}

.trigger:hover {
  color: #1890ff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar {
  cursor: pointer;
  background: #1890ff;
}

/* 标签页样式 */
.tabs-bar {
  height: 44px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  padding: 0 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.tabs-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  overflow-x: auto;
  overflow-y: hidden;
}

.tabs-container::-webkit-scrollbar {
  height: 0;
}

.tab-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 14px;
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 13px;
  color: #595959;
  white-space: nowrap;
  user-select: none;
}

.tab-item:hover {
  background: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.tab-item.active {
  background: #1890ff;
  border-color: #1890ff;
  color: #fff;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
}

.tab-icon {
  font-size: 14px;
}

.tab-title {
  font-weight: 500;
}

.tab-close {
  font-size: 12px;
  padding: 2px;
  border-radius: 2px;
  transition: all 0.2s;
  margin-left: 2px;
}

.tab-close:hover {
  background: rgba(0, 0, 0, 0.1);
}

.tab-item.active .tab-close:hover {
  background: rgba(255, 255, 255, 0.2);
}

.tabs-actions {
  margin-left: 8px;
  padding-left: 8px;
  border-left: 1px solid #e8e8e8;
}

.tabs-action-icon {
  font-size: 14px;
  color: #595959;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.tabs-action-icon:hover {
  background: #f0f0f0;
  color: #1890ff;
}

.layout-content {
  margin: 16px;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 172px);
}
:deep(.ant-avatar-group) {
  display: flex;
  align-items: center;
  div {
    margin-left: 10px;
  }
}
</style>
